*===============================================================================
*Firm and Country Embedded Productivity (Alviarez, Cravino and Ramondo) 
*Last Modified by Vanessa Alviarez 02/2022
*Description: Aggregate the estimates from the gravity regressions to recover the set of fixed effects: aggregate, MANUF/SERVICES (NAICS2 and NAICS4)
*Calculate the An by calculating the weight average of Anj, where weights are equal to the sectorial expenditure share in each country
*Notes: (1) To construct the aggregate, An, we are only using country sector estimates Anj that are estimated using MNCs with 3 or more affiliates and for which we know the parent company  
*(2) Renormalize the theta_nj (sectorial expenditure shares in country n). We only keep countries with information in all sectors. Notice I re-normalize, but I will not use countries with less than 15 sectors
*===============================================================================

*This file produces aggregate coefficientes for 
*-----------------------------------------------------------
*if "`typeused'"=="agg" 
*if "`typeused'"=="aggDAonly"
*if "`typeused'"=="exclnonmarket"
*if "`typeused'"=="MS"
*if "`typeused'"=="type"
*if "`weightused'"=="FR" 


********************************************************
local min_num_aff=3
local min_num_parent=1
global public ""
*`" drop if sector=="Public_Administration (O)" "'
********************************************************

/* For dubugging the code
global lf "LF"
local ending ""
local zz naics  
local var0 "_sales" 
local name "_base" 
local name1 "" 
local samp=4  
local title "`zz'`var0'_s`samp'`name'`name1'`ending'"
display "`title'"
global ctryrel FR
local period "2016"
local y=2016
local min_num_aff=3
local min_num_parent=1
global public ""
use "${output}/estimates_sec_naics_sales_s4_base_woparent.dta", clear 
*/


capture log close
log using "${tfp}/code/aggregates_`title'.smcl", replace 
**************************************
/*
local ending "_all"
local zz naics 
local varinterest sales_exp
local var0 "_`varinterest'" 
local name "_base"
local name1 "_exclexp_alt" 
local samp=4  
local title "`zz'`var0'_s`samp'`name'`name1'`ending'"
display "`title'"
local y=2016
*/

*===============================================================================
*AGGREGATING Anj ESTIMATES for the overall economy
*===============================================================================
if "`typeused'"=="agg" {


*Display relevant locals 
*-------------------------------------------------------------------------------
display "LF: $lf"
display "Title: `title'"
display "Country relative: $ctryrel"
display `"Year: `period'"'


*Open the base clean data file and provide a number to each sector
*-------------------------------------------------------------------------------
display "sin_firmlevel_`zz'_gravity${lf}`ending'" 
clear all
use "${output}/sin_firmlevel_`zz'_gravity${lf}`ending'.dta", clear
$public
$nonmarket 
keep sector
sort sector
duplicates drop
gen sec_num=_n
tempfile sec_num
save `sec_num', replace


*Looping across each year 
*-------------------------------------------------------------------------------
foreach y in `period' {
display "`y'"


*Bring the weights and replace missing with zeros 
*-------------------------------------------------------------------------------
use "${output}/sector_weights.dta", clear
fillin isocode sector year
keep if year==`y'

foreach v in theta theta_fr theta_mso theta_mso_fr {
display "`v'"
replace `v'=0 if `v'==.
}
tempfile weights
save `weights', replace


*Open the file with the sectoral estimates (from the previous step) only to get the list of country-sector pairs for which we have estimates
*-------------------------------------------------------------------------------
use "${output}/estimates_sec_`title'.dta", clear
keep if year==`y'
$public


*Check how many of the estimates are using MNCs with less than 3 affiliates and without known parents (listed in Orbis)
table sector isocode if num_aff<`min_num_aff'
replace D_Waugh=. if num_aff<`min_num_aff'
replace D_EK=.  if num_aff<`min_num_aff' | num_parents<`min_num_parent'

merge m:1 year isocode type sector using `weights', keepusing(theta*)
drop if _merge==2
drop _merge


*Renormalize the theta_nj (sectorial expenditure shares in country n). We only keep countries with information in all sectors. Notice I re-normalize, but I will not use countries with less than 15 sectors
*-------------------------------------------------------------------------------
by table isocode year, sort: egen sector_count=count(D_Waugh) 
tab sector_count
tab isocode if sector_count<15
by table isocode year, sort: egen sector_count_EK=count(D_EK) 
tab sector_count_EK
tab isocode if sector_count_EK<15

foreach j in D_Waugh D_EK {
foreach i in theta theta_fr {
display "`i'"
display "`j'"
gen ii=`i' if `j'!=. 
by table isocode year, sort: egen xx=total(ii) 
gen `i'_`j'=ii/xx
replace `i'_`j'=0 if `i'_`j'==.
drop ii xx 
}
}
tempfile weights2
save `weights2', replace


*Create locals for each country-sector pair, with information (estimates)
*-------------------------------------------------------------------------------
levelsof isocode, local(iso2) 
foreach iso3 of local iso2 {

use `weights2', clear
keep if isocode=="`iso3'"
merge 1:1 sector using `sec_num'
drop if _merge==2
drop _merge

          
*Save the re-normalized weight in a local with isocode-sector labeled 
*For Waught and EK, for the country in question and France
*-------------------------------------------------------------------------------
levelsof sec_num, local(gg2) 
foreach gg3 of local gg2 {

*Waugh
*----------------
sum theta_D_Waugh if isocode=="`iso3'" & sec_num==`gg3'
local wgt_Waugh_iso`iso3'sec`gg3'=`r(mean)'
display "`wgt_Waugh_iso`iso3'sec`gg3''"

sum theta_fr_D_Waugh if isocode=="`iso3'" & sec_num==`gg3'
local wgtfr_Waugh_iso`iso3'sec`gg3'=`r(mean)'
display "`wgtfr_Waugh_iso`iso3'sec`gg3''"

*EK
*----------------
sum theta_D_EK if isocode=="`iso3'" & sec_num==`gg3'
local wgt_EK_iso`iso3'sec`gg3'=`r(mean)'
display "`wgt_EK_iso`iso3'sec`gg3''"

sum theta_fr_D_EK if isocode=="`iso3'" & sec_num==`gg3'
local wgtfr_EK_iso`iso3'sec`gg3'=`r(mean)'
display "`wgtfr_EK_iso`iso3'sec`gg3''"
}
}
*

*-------------------------------------------------------------------------------
*Obtaining standard errors: Now in order to get stardard errors for the weighted An, we need to run the sectoral regressions again and use the PostEstimation lincom Stata command which computes point estimates, standard errors, etc for linear combinations of coefficients after any estimation command. 
*-------------------------------------------------------------------------------
*Notice: this is the file we create right before run the sectoral regressions. A lot of the process below is the same we do in the baseline FE regressions
use "${output}/pre_reg0_`title'_`y'.dta", clear  
drop type 

*Drop the dummies corresponding to the country of reference in order to have country FE relative to the Reference Country (France in this case) 
foreach v of varlist aiso*sec* {
display "`v'"
       local x : variable label `v'
        if strpos("`x'", "$ctryrel/")>0 drop `v' 
}
*

*Run the FE regression only to get the list of isocode in the e(sample) and initialize the LOOP ACROSS ISOCODES
reghdfe lhs2 aiso*sec* piso*sec* $ind_var, abs(`absFEreg', savefe) vce(cluster double_cluster) residuals(resid)
gen esample=e(sample)
keep if esample==1
drop esample

levelsof isocode, local(isolist) 
local not FR
local isolist: list isolist- not


*Generate aggregated point estimates with their corresponding standard errors (DA) --storage them in a macro--
*------------------------------------------------------------------------------
gen b1=.
gen s1=.
foreach xx of local isolist {

local cc "`xx'"
display "***`cc'***"

*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*
preserve
use "${output}/pre_reg0_`title'_`y'.dta", clear  
set matsize 11000
keep if year==`y'

*Country-sector dummy
keep if isocode=="`cc'" | isocode=="FR"
keep isocode sector
duplicates drop
gen i=1
reshape wide i, i(sector) j(isocode) string
keep if iFR!=. & i`cc'!=.
keep sector

merge 1:1 sector using `sec_num'
drop if _merge==2
drop _merge
rename sec_num id
sum id
local sse=`r(max)'
levelsof id, local(id2) 
local selectsector

foreach ii of local id2 {
display "`xx'; `ii'"
local selectsector `selectsector' `ii' 
}
display "`selectsector'"
restore
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*

*Now add the weights and the variable of interest (for all sectors in a country sequentially) 
display "`selectsector'"
local w1: word 1 of `selectsector'
display "`w1'"
local selectsector2 : list selectsector -w1
display "`selectsector2'"

local terms `wgt_Waugh_iso`cc'sec`w1''*aiso`cc'sec`w1'
display "`terms'"
lincom `wgt_Waugh_iso`cc'sec`w1''*aiso`cc'sec`w1'
foreach ll of local selectsector2 {
    local terms `terms' + `wgt_Waugh_iso`cc'sec`ll''*aiso`cc'sec`ll'
    lincom `terms'
}
*
replace b1=`r(estimate)' if isocode=="`cc'" 
replace s1=`r(se)' if isocode=="`cc'"
}
rename b1 D_A
rename s1 D_A_se


*Generate aggregated point estimates with their corresponding standard errors (DP) 
*-------------------------------------------------------------------------------
gen b1=.
gen s1=.
*foreach xx in "AT" "BE" "BG" "CZ" "DE" "EE" "ES" "FI" "GB" "GR" "HR" "HU" "IT" "JP" "KR" "LT" "LV" "MX" "NL" "PL" "PT" "RO" "SE" "SI" "SK" {
foreach xx of local isolist {

local cc "`xx'"
local ccref "FR"
display "***`cc'***"

*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*
preserve
use "${output}/pre_reg0_`title'_`y'.dta", clear  
set matsize 11000

*Country-sector dummy
keep if isocode=="`cc'" | isocode=="FR"
keep isocode sector
gen i=1
duplicates drop
reshape wide i, i(sector) j(isocode) string
keep if iFR!=. & i`cc'!=.
keep sector

merge 1:1 sector using `sec_num'
drop if _merge==2
drop _merge
rename sec_num id
sum id
local sse=`r(max)'
levelsof id, local(id2) 
local selectsector
foreach ii of local id2 {
display "`xx'; `ii'"
local selectsector `selectsector' `ii' 
}
display "`selectsector'"
restore
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*

*Now add the weights and the variable of interest (for all sectors in a country sequentially) 
local selectsector2=substr("`selectsector'",2,.)
display "`selectsector'"
local w1: word 1 of `selectsector'
display "`w1'"
local selectsector2 : list selectsector -w1
display "`selectsector2'"

local terms `wgt_EK_iso`cc'sec`w1''*(piso`cc'sec`w1'-piso`ccref'sec`w1')
lincom `wgt_EK_iso`cc'sec`w1''*(piso`cc'sec`w1'-piso`ccref'sec`w1')
foreach ll of local selectsector2 {
    local terms `terms' + `wgt_EK_iso`cc'sec`ll''*(piso`cc'sec`ll'-piso`ccref'sec`ll')
    lincom `terms'
}
*
replace b1=`r(estimate)' if isocode=="`cc'" 
replace s1=`r(se)' if isocode=="`cc'"
}
rename b1 D_P
rename s1 D_P_se


*Save the information 
*-------------------------------------------------------------------------------
gen type="`typeused'"
keep year isocode type D_A D_A_se D_P D_P_se  
sort year isocode
duplicates drop
tempfile temp_DA_DP_DPinter
save `temp_DA_DP_DPinter', replace


*------------------------------------------------------
*Append DP-DA (point estimates and estandar errors) and bring the ctte, R2, RSS and number of observations.
*------------------------------------------------------
use `temp_DA_DP_DPinter', clear
merge m:1 year using "${output}/R2_`title'.dta", keepusing(num_obs num_full num_sing mss mdf rss rdf rms num_FE R2 R2adj R2w R2wadj)
drop if _merge==2
drop _merge
merge m:1 year using "${output}/ctte_`title'.dta", keepusing(*ctte*)
drop if _merge==2
drop _merge
order year isocode type
sort year isocode 

foreach x in D_A D_A_se D_P D_P_se   {
replace `x'=0 if isocode=="$ctryrel"
replace `x'=. if `x'==0 & isocode!="$ctryrel"
}

gen table="`title'"

if "`name'"=="_base" {
replace type="total" 
}
if "`name'"=="_exclnomark" {
replace type="market" 
}
save "${output}/estimates_`typeused'_`title'_`y'.dta", replace 
}
*
clear all
set obs 1
foreach y in `period' {
append using "${output}/estimates_`typeused'_`title'_`y'.dta"
}
drop if year==.
sum D_A
save "${output}/estimates_`typeused'_`title'.dta", replace 

foreach y in `period' {
erase "${output}/estimates_`typeused'_`title'_`y'.dta"
}
*

}
*





*===============================================================================
*BY TYPE AGGREGATED COEFFICIENTS
*===============================================================================

/*
local zz naics  
local var0 "_sales" 
local name "_base" 
local name1 "_check"
local ending "_all"
local samp=4

local title "`zz'`var0'_s`samp'`name'"
global ctryrel FR
local period "2016"
global nonmarket `" drop if sector1=="Non-Market Economy" "'
*/

if "`typeused'"=="type" {


*Display relevant locals 
*-------------------------------------------------------------------------------
display "LF: $lf"
display "Title: `title'"
display "Country relative: $ctryrel"
display `"Year: `period'"'
display "`typeused'"

*Open the base clean data file and provide a number to each sector
*-------------------------------------------------------------------------------
display "sin_firmlevel_`zz'_gravity${lf}`ending'" 
clear all
use "${output}/sin_firmlevel_`zz'_gravity${lf}`ending'.dta", clear
$public
$nonmarket 
keep sector
sort sector
duplicates drop
gen sec_num=_n
tempfile sec_num
save `sec_num', replace


*Looping across each year 
*-------------------------------------------------------------------------------
foreach y in `period' {
display "`y'"


*Bring the weights and replace missing with zeros 
*-------------------------------------------------------------------------------
use "${output}/sector_weights.dta", clear
fillin isocode sector year
keep if year==`y'

foreach v in theta theta_fr theta_mso theta_mso_fr {
display "`v'"
replace `v'=0 if `v'==.
}
tempfile weights
save `weights', replace


*Open the file with the sectoral estimates (from the previous step) only to get the list of country-sector pairs for which we have estimates
*-------------------------------------------------------------------------------
use "${output}/estimates_sec_`title'.dta", clear
keep if year==`y'
$public


*Check how many of the estimates are using MNCs with less than 3 affiliates and without known parents (listed in Orbis)
table sector isocode if num_aff<`min_num_aff'
replace D_Waugh=. if num_aff<`min_num_aff'
replace D_EK=.  if num_aff<`min_num_aff' | num_parents<`min_num_parent'

merge m:1 year isocode type sector using `weights', keepusing(theta*)
drop if _merge==2
drop _merge


*Renormalize the theta_nj (sectorial expenditure shares in country n). We only keep countries with information in all sectors. Notice I re-normalize, but I will not use countries with less than 15 sectors
*-------------------------------------------------------------------------------
by table isocode year, sort: egen sector_count=count(D_Waugh) 
tab sector_count
tab isocode if sector_count<15
by table isocode year, sort: egen sector_count_EK=count(D_EK) 
tab sector_count_EK
tab isocode if sector_count_EK<15

foreach j in D_Waugh D_EK {
foreach i in theta theta_fr {
display "`i'"
display "`j'"
gen ii=`i' if `j'!=. 
by table isocode year `typeused', sort: egen xx=total(ii) 
gen `i'_`j'=ii/xx
replace `i'_`j'=0 if `i'_`j'==.
drop ii xx 
}
}
tempfile weights2
save `weights2', replace


*Create locals for each country-sector pair, with information (estimates)
*-------------------------------------------------------------------------------
levelsof isocode, local(iso2) 
foreach iso3 of local iso2 {

use `weights2', clear
keep if isocode=="`iso3'"
merge 1:1 sector using `sec_num'
drop if _merge==2
drop _merge

          
*Save the re-normalized weight in a local with isocode-sector labeled 
*For Waught and EK, for the country in question and France
*-------------------------------------------------------------------------------
levelsof sec_num, local(gg2) 
foreach gg3 of local gg2 {

*Waugh
*----------------
sum theta_D_Waugh if isocode=="`iso3'" & sec_num==`gg3'
local wgt_Waugh_iso`iso3'sec`gg3'=`r(mean)'
display "`wgt_Waugh_iso`iso3'sec`gg3''"

sum theta_fr_D_Waugh if isocode=="`iso3'" & sec_num==`gg3'
local wgtfr_Waugh_iso`iso3'sec`gg3'=`r(mean)'
display "`wgtfr_Waugh_iso`iso3'sec`gg3''"

*EK
*----------------
sum theta_D_EK if isocode=="`iso3'" & sec_num==`gg3'
local wgt_EK_iso`iso3'sec`gg3'=`r(mean)'
display "`wgt_EK_iso`iso3'sec`gg3''"

sum theta_fr_D_EK if isocode=="`iso3'" & sec_num==`gg3'
local wgtfr_EK_iso`iso3'sec`gg3'=`r(mean)'
display "`wgtfr_EK_iso`iso3'sec`gg3''"
}
}
*

*-------------------------------------------------------------------------------
*Obtaining standard errors: Now in order to get stardard errors for the weighted An, we need to run the sectoral regressions again and use the PostEstimation lincom Stata command which computes point estimates, standard errors, etc for linear combinations of coefficients after any estimation command. 
*-------------------------------------------------------------------------------
*Notice: this is the file we create right before run the sectoral regressions. A lot of the process below is the same we do in the baseline FE regressions
use "${output}/pre_reg0_`title'_`y'.dta", clear  
drop type 

*Drop the dummies corresponding to the country of reference in order to have country FE relative to the Reference Country (France in this case) 
foreach v of varlist aiso*sec* {
display "`v'"
       local x : variable label `v'
        if strpos("`x'", "$ctryrel/")>0 drop `v' 
}
*

*Run the FE regression only to get the list of isocode in the e(sample) and initialize the LOOP ACROSS ISOCODES
reghdfe lhs2 aiso*sec* piso*sec* $ind_var, abs(`absFEreg', savefe) vce(cluster double_cluster) residuals(resid)
gen esample=e(sample)
keep if esample==1
drop esample

levelsof isocode, local(isolist) 
local not FR
local isolist: list isolist- not


display "*-----------------------  MACRO SECTORS ----------------------*"
*levelsof isocode, local(isolist) 
gen type="NA"
replace type="manuf" if sector1=="Manufacturing (C)"
replace type="nonmarket" if sector1=="Non-Market Economy"
replace type="others" if sector1=="Other_Goods (A-B-D-E-F)"
replace type="serv" if sector1=="Market_Services (G-H-I-J-K-M-N-R-S-T)"
tab type 

levelsof type, local(typelist) 
local not nonmarket
local typelist : list typelist- not
*foreach ll of local typelist {
*foreach xx of local isolist {
*foreach ll in manuf nonmarket others serv {




display "DA: Generate aggregated point estimates with their corresponding standard errors"
*------------------------------------------------------------------------------
foreach www of local typelist {


gen b1=.
gen s1=.
foreach xx of local isolist {

display "DA; `www'; `xx'"
local cc "`xx'"
display "***`cc'***"

*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*
preserve
use "${output}/pre_reg0_`title'_`y'.dta", clear  
set matsize 11000
keep if isocode=="`cc'" & type=="`www'"
local observ=_N
display "`observ'"
restore

*==========================================================================
if `observ'>0 {

preserve
use "${output}/pre_reg0_`title'_`y'.dta", clear  
set matsize 11000

*Country-sector dummy
keep if (isocode=="`cc'" | isocode=="FR") & type=="`www'"
keep isocode sector
gen i=1
duplicates drop
reshape wide i, i(sector) j(isocode) string
keep if iFR!=. & i`cc'!=.
keep sector
duplicates drop


merge 1:1 sector using `sec_num'
drop if _merge==2
drop _merge
rename sec_num id
sum id
local sse=`r(max)'
levelsof id, local(id2) 
local selectsector
foreach ii of local id2 {
display "`xx'; `ii'"
local selectsector `selectsector' `ii' 
}
display "`selectsector'"
restore

*======================================================================
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*

*Now add the weights and the variable of interest (for all sectors in a country sequentially) 
display "`selectsector'"
local w1: word 1 of `selectsector'
display "`w1'"
local selectsector2 : list selectsector -w1
display "`selectsector2'"

local terms `wgt_Waugh_iso`cc'sec`w1''*aiso`cc'sec`w1'
display "`terms'"
lincom `wgt_Waugh_iso`cc'sec`w1''*aiso`cc'sec`w1'
foreach ll of local selectsector2 {
    local terms `terms' + `wgt_Waugh_iso`cc'sec`ll''*aiso`cc'sec`ll'
    lincom `terms'
}
*
replace b1=`r(estimate)' if isocode=="`cc'" 
replace s1=`r(se)' if isocode=="`cc'"
}
else {
replace b1=0 if isocode=="`cc'"  
replace s1=0 if isocode=="`cc'"
}
}
rename b1 D_A_`www'
rename s1 D_A_se_`www'



*Generate aggregated point estimates with their corresponding standard errors (DP) 
*-------------------------------------------------------------------------------
gen b1=.
gen s1=.
*foreach xx in "AT" "BE" "BG" "CZ" "DE" "EE" "ES" "FI" "GB" "GR" "HR" "HU" "IT" "JP" "KR" "LT" "LV" "MX" "NL" "PL" "PT" "RO" "SE" "SI" "SK" {
foreach xx of local isolist {

display "DP; `www'; `xx'"
local cc "`xx'"
display "***`cc'***"
local ccref "FR"


*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*
preserve
use "${output}/pre_reg0_`title'_`y'.dta", clear  
set matsize 11000
keep if isocode=="`cc'" & type=="`www'"
local observ=_N
display "`observ'"
restore

*==========================================================================
if `observ'>0 {

preserve
use "${output}/pre_reg0_`title'_`y'.dta", clear  
set matsize 11000

*Country-sector dummy
keep if (isocode=="`cc'" | isocode=="FR") & type=="`www'"
keep isocode sector
gen i=1
duplicates drop
reshape wide i, i(sector) j(isocode) string
keep if iFR!=. & i`cc'!=.
keep sector
duplicates drop

merge 1:1 sector using `sec_num'
drop if _merge==2
drop _merge
rename sec_num id
sum id
local sse=`r(max)'
levelsof id, local(id2) 
local selectsector
foreach ii of local id2 {
display "`xx'; `ii'"
local selectsector `selectsector' `ii' 
}
display "`selectsector'"
restore

*======================================================================
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*==*=*

*Now add the weights and the variable of interest (for all sectors in a country sequentially) 
local selectsector2=substr("`selectsector'",2,.)
display "`selectsector'"
local w1: word 1 of `selectsector'
display "`w1'"
local selectsector2 : list selectsector -w1
display "`selectsector2'"

local terms `wgt_EK_iso`cc'sec`w1''*(piso`cc'sec`w1'-piso`ccref'sec`w1')
lincom `wgt_EK_iso`cc'sec`w1''*(piso`cc'sec`w1'-piso`ccref'sec`w1')
foreach ll of local selectsector2 {
    local terms `terms' + `wgt_EK_iso`cc'sec`ll''*(piso`cc'sec`ll'-piso`ccref'sec`ll')
    lincom `terms'
}
*
replace b1=`r(estimate)' if isocode=="`cc'" 
replace s1=`r(se)' if isocode=="`cc'"
}
else {
replace b1=0 if isocode=="`cc'"  
replace s1=0 if isocode=="`cc'"
}
}
rename b1 D_P_`www'
rename s1 D_P_se_`www'

*Ending of typelist
}
*Ending of typelist



display "Save the information"
*-------------------------------------------------------------------------------
keep year isocode D_A* D_A_se* D_P* D_P_se*  
sort year isocode
duplicates drop

reshape long D_A_ D_A_se_ D_P_ D_P_se_ D_Pinter_ D_Pinter_se_, i( year isocode ) j(type) string
foreach x in D_A D_A_se D_P D_P_se D_Pinter D_Pinter_se {
display "`x'"
rename `x'_ `x'
}

tempfile temp_DA_DP_DPinter
save `temp_DA_DP_DPinter', replace



*------------------------------------------------------
*Append DP-DA (point estimates and estandar errors) and bring the ctte, R2, RSS and number of observations.
*------------------------------------------------------
use `temp_DA_DP_DPinter', clear
merge m:1 year using "${output}/R2_`title'.dta", keepusing(num_obs num_full num_sing mss mdf rss rdf rms num_FE R2 R2adj R2w R2wadj)
drop if _merge==2
drop _merge
merge m:1 year using "${output}/ctte_`title'.dta", keepusing(*ctte*)
drop if _merge==2
drop _merge
order year isocode type
sort year isocode 

foreach x of varlist D_A* D_A_se* D_P* D_P_se*   {
replace `x'=0 if isocode=="$ctryrel"
replace `x'=. if `x'==0 & isocode!="$ctryrel"
}

gen table="`title'"
save "${output}/estimates_agg`typeused'_`title'_`y'.dta", replace 
}
*

clear all
set obs 1
foreach y in `period' {
append using "${output}/estimates_agg`typeused'_`title'_`y'.dta"
}
drop if year==.
sum D_A
save "${output}/estimates_agg`typeused'_`title'.dta", replace 

foreach y in `period' {
erase "${output}/estimates_agg`typeused'_`title'_`y'.dta"
}

*
}



*--------------------------------
log close 